<template>
	<view>
		<!-- 页面头部 -->
		<view class="main-header" :style="{ height: platform == 'H5' ? '60rpx' : '320rpx', paddingTop: platform == 'H5' ? '0' : '80rpx' }" style="background-color: #f3f3f3;">
		  <!-- <image class="bg-image" src="/static/background/1741683261884.jpg" mode="scaleToFill"></image> -->
		  <!-- 用户信息 -->
		  <view v-if="isLogin" class="user-info">
		    <view class="user-avatar" @click="handlePersonal()">
		      <!-- <avatar-image :url="userInfo.avatar_url" :width="100" /> -->
		    </view>
		    <view class="user-content">
		      <!-- 会员昵称 -->
		      <view class="nick-name oneline-hide" @click="handlePersonal()" style="color: #000000;font-size: 0.8rem;">用户:{{ userInfo.nick_name }}</view>
		      <!-- 会员等级 -->
		      <view v-if="$checkModule('user-grade') && userInfo.grade_id > 0 && userInfo.grade" class="user-grade">
		        <view class="user-grade_icon">
		          <image class="image"
		            src="">
		          </image>
		        </view>
		        <view class="user-grade_name">
		          <text>{{ userInfo.grade.name }}</text>
		        </view>
		      </view>
		      <!-- 会员无等级时显示手机号 -->
		      <!-- <view v-else class="mobile">{{ userInfo.mobile }}</view> -->
		    </view>
		  </view>
		  <!-- 未登录 -->
		  <view v-else class="user-info" @click="handleLogin">
		    <view class="user-avatar">
		      <avatar-image :width="100" />
		    </view>
		    <view class="user-content" style="color: #ffffff;">
		      <view class="nick-name">未登录</view>
		      <view class="login-tips">点击登录账号</view>
		    </view>
		  </view>
		</view>
		
		<!-- 绑定手机号 -->
		<!-- <view v-if="isLogin && !userInfo.mobile && setting[SettingKeyEnum.REGISTER.value].isManualBind" class="my-mobile"
		  @click="handleBindMobile()">
		  <view class="info">点击绑定手机号，确保账户安全</view>
		  <view class="btn-bind">去绑定</view>
		</view> -->
		
		<!-- 积分板块 -->
		<view v-if="$checkModules(['market-recharge', 'market-points', 'market-coupon'])" class="my-asset">
		  <view class="asset-left flex-box dis-flex flex-x-around">
		    	
			<!-- 应用积分 -->
			<view v-if="$checkModule('market-recharge')" class="asset-left-item" style="max-width: 200rpx;">
		      <view class="item-value dis-flex flex-x-center">
	    	<!--<text class="oneline-hide">{{ isLogin ? appPoints : '--' }}</text> -->
		        <text class="oneline-hide">{{ isLogin ? userInfo.app_points : '--' }}</text>
		      </view>
		      <view class="item-name dis-flex flex-x-center">
		        <text>{{$t('index.application-points')}}</text>
		      </view>
		    </view>
			
			<!-- 积分转换按钮 -->
			<view v-if="$checkModule('market-coupon')" class="asset-left-item" @click="openCustomDialog">
			    <view class="item-value dis-flex flex-x-center">
			      <img src="/static/exchange.png" style="width: 30px;">
			    </view>
			    <view class="item-name dis-flex flex-x-center">
			      <text>{{this.pointsRate}}:1</text>
			    </view>
			</view>
			
			<!-- 积分转换弹框 -->
			<view v-if="showDialog" class="dialog" style="background-color: #fafafa;width: 90%;height: 500rpx;">
				  <view style="border-bottom: 1px solid #e9e9e9;display: flex;justify-content: space-between;padding: 20rpx;">
				    <span style="font-size: 35rpx;">积分转换</span>
				    <span style="font-size: 35rpx;" @click="closeDialog">×</span>
				  </view>
			      <input class="uni-input exchang-input" type="number" min="0" v-model="inputValue" @input.native="onInput" placeholder="输入要转换的应用积分"/>
				  <p style="margin: 0 auto;width: 90%;"><span style="color: red;">*</span>可获得{{pValue}}商城积分</p>
				  <view style="margin-top: 80rpx;display: flex;justify-content: center;">
					  <!-- <button class="mini-btn" type="default" size="mini" @click="closeDialog">取消</button> -->
					  <button class="mini-btn" type="primary" size="mini" @click="confirmDialog" style="margin-left: 10px;width: 90%;background-color: #ff6335;height: 70rpx;line-height: 70rpx;">确定</button>
				  </view>
			</view>
			
			<!-- 商城积分 -->
		    <view v-if="$checkModule('market-points')" class="asset-left-item" @click="onTargetPoints">
		      <view class="item-value dis-flex flex-x-center">
		        <text class="oneline-hide">{{ isLogin ? assets.points : '--' }}</text>
		      </view>
		      <view class="item-name dis-flex flex-x-center">
		        <!-- <text>{{ setting[SettingKeyEnum.POINTS.value].points_name }}</text> -->
		        <text>{{$t('index.mall-points')}}</text>
		      </view>
		    </view>
		  
		 </view>
		</view>
		
		<!-- usdt/paypal -->
		<view style="display: flex;  justify-content: space-around;padding: 10px 0;border-top:1px solid #e9e9e9;">
			<view @click="onTargetUsdt" style="width: 48%; ">
			    <img src="/static/background/usdt.jpg" style="width: 100%;border-radius: 10px;">
			</view>
			<view @click="onTargetPayPal" style="width: 48%; ">
				<img src="/static/background/paypal.jpg" style="width: 100%;border-radius: 10px;" >
			</view>
		</view>
		
	</view>
</template>

<script>
  import store from '@/store'
  import { inArray } from '@/utils/util'
  import AvatarImage from '@/components/avatar-image'
  import CustomerBtn from '@/components/customer-btn'
  import { setCartTabBadge } from '@/core/app'
  import SettingKeyEnum from '@/common/enum/setting/Key'
  import StoreModel from '@/common/model/Store'
  import SettingModel from '@/common/model/Setting'
  import * as UserApi from '@/api/user'
  import * as OrderApi from '@/api/order'
  import * as PointsApi from '@/api/points'
  import { checkLogin, filterModules } from '@/core/app'

  export default {
    components: {
      AvatarImage,
      CustomerBtn
    },
    data() {
      return {
        inArray,
        // 枚举类
        SettingKeyEnum,
        // 正在加载
        isLoading: true,
        // 首次加载
        isFirstload: true,
        // 是否已登录
        isLogin: false,
        // 系统设置
        setting: {},
        // 当前用户信息
        userInfo: {},
        // 账户资产
        assets: { balance: '--', points: '--', coupon: '--' },
		// 控制弹窗显示隐藏
		showDialog: false, 
		// 输入框绑定的值
		inputValue: '', 
		// 显示可获得的商城积分
		pValue:0,
		// 后台设置的积分兑换比例
		pointsRate:0,
		// 后台设置的积分兑换比例
		appPoints:0,
		// appid
		appid:0
      }
    },
	
	
	async created() {
		 this.onRefreshPage();
	},
	
    methods: {

      // 刷新页面
      onRefreshPage() {
		// 获取appid设置appid
		const app = this
		uni.getStorage({
			key: 'appid',
			success: function (res) {
				console.log(res.data);
				app.appid=res.data;
			}
		}); 
        // 更新购物车角标
        setCartTabBadge()
        // 判断是否已登录
        this.isLogin = checkLogin()
        // 获取页面数据
        this.getPageData()
      },

      // 获取页面数据
      getPageData(callback) {
        const app = this
        app.isLoading = true
        Promise.all([app.getSetting(), app.getUserInfo(), app.getUserAssets(),app.getAppInfo()])
          .then(result => {
            app.isFirstload = false
            // 初始化我的服务数据
            app.initService()
            // 初始化订单操作数据
            app.initOrderTabbar()
            // 执行回调函数
            callback && callback()
          })
          .catch(err => console.log('catch', err))
          .finally(() => app.isLoading = false)
      },

      // 获取商城设置
      getSetting() {
        const app = this
        return new Promise((resolve, reject) => {
          SettingModel.data()
            .then(setting => {
              app.setting = setting
              resolve(setting)
            })
            .catch(reject)
        })
      },

      // 获取当前用户信息
      getUserInfo() {
        const app = this
        return new Promise((resolve, reject) => {
          !app.isLogin ? resolve(null) : UserApi.info({}, { load: app.isFirstload })
            .then(result => {
              app.userInfo = result.data.userInfo
              resolve(app.userInfo)
            })
            .catch(err => {
              if (err.result && err.result.status == 401) {
                app.isLogin = false
                resolve(null)
              } else {
                reject(err)
              }
            })
        })
      },

      // 获取账户资产
      getUserAssets() {
        const app = this
        return new Promise((resolve, reject) => {
          !app.isLogin ? resolve(null) : UserApi.assets({}, { load: app.isFirstload })
            .then(result => {
              app.assets = result.data.assets
              resolve(app.assets)
            })
            .catch(err => {
              if (err.result && err.result.status == 401) {
                app.isLogin = false
                resolve(null)
              } else {
                reject(err)
              }
            })
        })
      },
	  
	  // 显示弹窗
	  openCustomDialog() {
		if(!this.isLogin){
		  uni.showToast({
			title: '请先登录',
			icon: 'none',
			duration: 2000
		  });
		  return false;
		}
	    this.showDialog = true; 
	  },
	  // 关闭弹窗并清空输入值
	  closeDialog() {
	    this.showDialog = false; 
	    this.inputValue = '';
	    this.pValue = 0;
	  },
	  // 积分兑换提交按钮
	  confirmDialog() {
		if(!this.inputValue){
			uni.showToast({
				title: '请输入需兑换的积分',
				icon: 'none',
				duration: 2000
			});
			
		    return false;
		}
	    this.doExchang(this.appid,this.inputValue);
	    this.pValue = 0;
	    this.closeDialog(); // 关闭弹窗并清空输入值
	  },
	  // 检测兑换input框
	  onInput(event) {
		if(this.inputValue.indexOf(".")!== -1){  
			uni.showToast({
				title: '只能输入正整数',
				icon: 'none',
				duration: 2000
			});
			this.inputValue = '';
			this.pValue = 0;
			return false;
		}
		  
		if(this.inputValue<=0||this.inputValue>parseInt(this.userInfo.app_points)){
		   uni.showToast({
			  title: '超出积分兑换范围',
			  icon: 'none',
			  duration: 2000
		   });
		   this.inputValue = '';
		   this.pValue = 0;
		   return false;
		}
		this.pValue=this.inputValue/this.pointsRate
	  },
	  
	  // 获取应用信息
	  getAppInfo() {
	   const app = this
	   return new Promise((resolve, reject) => {
	      PointsApi.getAppInfo({'appid':app.appid})
	       .then(result => {
	         app.pointsRate=result.data.points_rate;//兑换汇率
	         app.appPoints=0;//当前用户应用积分
	       })
	       .catch(err => {
	          if (err.result && eruer.result.status == 401) {
	            app.isLogin = false
	            resolve(null)
	          } else {
	            reject(err)
	          }
	        })
	   })
	  },
	  
	  // 积分兑换操作
	  doExchang(appid,val) {
	   const app = this
	   return new Promise((resolve, reject) => {
	      PointsApi.add({'appid':appid,'value':val})
	       .then(result => {
			  uni.showToast({
			  	title: result.message,
			  	icon: 'none',
			  	duration: 2000
			  });
			  
			   setTimeout(() => {
				  this.onRefreshPage();
			   }, 2000); // 2000毫秒后执行
	       })
	       .catch(err => {
              if (err.result && eruer.result.status == 401) {
                app.isLogin = false
                resolve(null)
              } else {
                reject(err)
              }
            })
	   })
	  },

      // 跳转到登录页
      handleLogin() {
        !this.isLogin && this.$navTo('pages/login/index')
      },

      // 跳转到绑定手机号页面
      handleBindMobile() {
        this.$navTo('pages/user/bind/index')
      },

      // 跳转到修改个人信息页
      handlePersonal() {
        this.$navTo('pages/user/personal/index')
      },

      // 跳转到我的积分页面
      onTargetPoints() {
        this.$navTo('pages/points/log')
      },
	  
	  // 跳转到钱包页面
	  onTargetWallet() {
	    this.$navTo('pages/wallet/index')
	  },
	  
	  // 跳转到USDT
	  onTargetUsdt() {
		if(!this.isLogin){
			uni.showToast({
				title: '请先登录',
				icon: 'none',
				duration: 2000
			});
			return false;
		}
	    this.$navTo('pages/cash/usdt')
	  },
	  
	  // 跳转到PayPal
	  onTargetPayPal() {
		if(!this.isLogin){
			uni.showToast({
				title: '请先登录',
				icon: 'none',
				duration: 2000
			});
			return false;
		}
	    this.$navTo('pages/cash/paypal')
	  }
    },

  }
</script>

<style lang="scss" scoped>
  .container {
    padding-bottom: 60rpx;
  }

  // 页面头部
  .main-header {
    // background-color: #FBF7EF;
    position: relative;
    width: 100%;
    height: 280rpx;
    background-size: 100% 100%;
    overflow: hidden;
    display: flex;
    align-items: center;
    padding-left: 30rpx;

    .bg-image {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 0;
    }

    .user-info {
      display: flex;
      height: 100rpx;
      z-index: 1;

      .user-content {
        display: flex;
        flex-direction: column;
        justify-content: center;
        margin-left: 30rpx;
        color: #c59a46;

        .nick-name {
          font-size: 34rpx;
          font-weight: bold;
          max-width: 300rpx;
        }

        .mobile {
          margin-top: 15rpx;
          font-size: 28rpx;
        }

        .user-grade {
          align-self: baseline;
          display: flex;
          align-items: center;
          background: #3c3c3c;
          margin-top: 12rpx;
          border-radius: 10rpx;
          padding: 4rpx 12rpx;

          .user-grade_icon .image {
            display: block;
            width: 32rpx;
            height: 32rpx;
          }

          .user-grade_name {
            margin-left: 5rpx;
            font-size: 26rpx;
            color: #EEE0C3;
          }

        }

        .login-tips {
          margin-top: 12rpx;
          font-size: 30rpx;
        }

      }
    }
  }

  // 角标组件
  .item-badge {
    position: absolute;
    top: 0;
    right: 55rpx;
    // background: $main-bg;
    background: #fa2209;
    color: #fff;
    border-radius: 100%;
    min-width: 38rpx;
    height: 38rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1rpx;
    font-size: 24rpx;
  }

  // 我的钱包
  .my-asset {
    display: flex;
    background: #fff;
    padding: 40rpx 0;

    .asset-right {
      width: 200rpx;
      border-left: 1rpx solid #eee;
    }

    .asset-right-item {
      text-align: center;
      color: #545454;

      .item-icon {
        font-size: 44rpx;
      }

      .item-name {
        margin-top: 14rpx;
        font-size: 28rpx;
      }

    }

    .asset-left-item {
      max-width: 183rpx;
      text-align: center;
      color: #666;
      padding: 0 16rpx;

      .item-value {
        font-size: 34rpx;
        color: $main-bg;
      }

      .item-name {
        margin-top: 14rpx;
        font-size: 28rpx;
      }

    }

  }
  
  .dialog {
		position: fixed; /* 固定定位 */
		top: 50%; /* 垂直居中 */
		left: 50%; /* 水平居中 */
		transform: translate(-50%, -50%); /* 居中偏移 */
		width: 60%;
		background-color: white; /* 背景颜色 */
		padding: 10px; /* 内边距 */
		border-radius: 10px; /* 圆角 */
		box-shadow: 0 2px 12px rgba(0,0,0,0.1); /* 阴影 */
		z-index: 999
	}
	
	.exchang-input{
		border: 1px solid #e9e9e9;
		width: 85%;
		margin: 50rpx auto 20rpx auto;
		height: 80rpx;
		border-radius: 8px;
		padding: 0 10rpx;
	}
</style>